package com.zhangsheng.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.zhangsheng.api.CommonResult;
import com.zhangsheng.entity.model.Product;
import com.zhangsheng.sentinel.block.MysqlServiceBlock;
import com.zhangsheng.sentinel.fallback.MysqlServiceFallBack;
import com.zhangsheng.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 张晟
 * @version 1.0
 * @date 2023/2/20 14:14
 */
@RestController
@Slf4j
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/master/add")
    @SentinelResource(value = "masterAdd" ,
            blockHandlerClass = MysqlServiceBlock.class ,
            blockHandler = "masterAddBlock" ,
            fallbackClass = MysqlServiceFallBack.class ,
            fallback = "masterAddFallback")
    public CommonResult<Product> add(@RequestBody Product product){
        boolean result = productService.save(product);
        if (result){
            return CommonResult.success(product);
        }
        return CommonResult.failed("添加商品失败");
    }

    @GetMapping("/slave1/{id}")
    @SentinelResource(value = "getSlave1" ,
            blockHandlerClass = MysqlServiceBlock.class ,
            blockHandler = "getSlave1Block" ,
            fallbackClass = MysqlServiceFallBack.class ,
            fallback = "getSlave1Fallback")
    public CommonResult<Product> getSlave1(@PathVariable("id") Integer id){
        if (id <= 0){
            return CommonResult.failed("参数异常");
        }
        Product product = productService.selectBySlave1(id);
        if (product != null){
            return CommonResult.success(product);
        }
        return CommonResult.failed("查询slave1商品失败");
    }

    @GetMapping("/slave2/{id}")
    @SentinelResource(value = "getSlave2" ,
            blockHandlerClass = MysqlServiceBlock.class ,
            blockHandler = "getSlave2Block" ,
            fallbackClass = MysqlServiceFallBack.class ,
            fallback = "getSlave2Fallback")
    public CommonResult<Product> getSlave2(@PathVariable("id") Integer id){
        if (id <= 0){
            return CommonResult.failed("参数异常");
        }
        Product product = productService.selectBySlave2(id);
        if (product != null){
            return CommonResult.success(product);
        }
        return CommonResult.failed("查询slave2商品失败");
    }

}
